﻿
using JQuery.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Base = System.Web.UI.Page;

namespace JQuery
{
    public static partial class Extensions
    {
        /// <summary>
        /// Get the Page Key that represents the current page in the script includes collection
        /// </summary>
        /// <param name="Obj">Current Page object</param>
        /// <returns></returns>
        internal static string GetPageKey(this Base Obj)
        {
            string path = Obj.Request.Url.AbsolutePath;
            return path
                    .Substring(0, path.IndexOf('?') > -1 ? path.IndexOf('?') - 1 : path.Length)
                    .Replace(Obj.Request.ApplicationPath, "")
                    .Replace("/", "_")
                    .ToLower();
        }

        public static ResourceManager ResourceIncludes(this Base Obj)
        {
            string page_key = GetPageKey(Obj);

            ResourceManager ScriptIncludes = null;

            if (Obj is Page)
            {
                ScriptIncludes = ((Page)Obj).ScriptIncludes;
            }
            else
            {
                if (Obj.Application["pages"] == null)
                {
                    Obj.Application["pages"] = new PageManager();
                }
                // pull the script includes dictionary
                if (((PageManager)Obj.Application["pages"])[page_key] == null)
                {
                    ((PageManager)Obj.Application["pages"])[page_key] = ScriptIncludes = new ResourceManager();
                }
                else
                {
                    ScriptIncludes = ((PageManager)Obj.Application["pages"])[page_key] as ResourceManager;
                }
            }

            return ScriptIncludes;
        }

        public static ExtensionContainer JQNExtensions(this Base Obj)
        {
            return Module.Composition;
        }

        public static void RegisterResourceInclude(this Base Obj, string id, string uri = "", string type = "text/javascript", int ordinal = 0, Assembly assembly = null)
        {
            Resource.Content oContent = Module.Manager[Module.Manager.GetResourceKey(id.Trim('/', '\\', ' '), type)];

            if(oContent != null)
            {
                Obj.ResourceIncludes().Add(oContent);
            }
            else if (uri.IsNotNullOrEmpty())
            {
                Obj.ResourceIncludes().Add(new Resource.Content(id.Trim('/', '\\', ' '), uri, type, assembly) { ordinal = ordinal, owner = Module.Manager });
            }
            else
            {
                throw new InvalidOperationException(String.Format("Resource content with the key '{0}', is not available.", id));
            }
        }
    }
}
